import os
import uuid
import json
import requests
from typing import Dict, Any, List, Optional
from src.modules.file_manager import FileManager
from src.modules.watermark_generator import WatermarkGenerator
from src.database.dao_factory import DAOFactory
from src.config import PUBLIC_BASE_DIR, VIDEO_DIR
from src.utils.logger import log_info, log_error

class WatermarkController:
    """视频水印处理控制器"""
    
    def __init__(self):
        """初始化控制器"""
        self.generator = WatermarkGenerator()
        self.dao_factory = DAOFactory.get_instance()
    
    def add_watermark_to_uploaded_video(
        self,
        video_file,
        text: str,
        font_size: int = 36,
        font_color: str = "white",
        opacity: float = 0.3,
        movement_type: str = "random",
        speed: float = 1.0
    ) -> Dict[str, Any]:
        """
        为上传的视频添加浮动透明水印
        
        Args:
            video_file: 上传的视频文件对象
            text: 水印文本
            font_size: 字体大小
            font_color: 字体颜色
            opacity: 不透明度
            movement_type: 移动类型
            speed: 移动速度
        
        Returns:
            处理结果
        """
        try:
            # 检查输入
            if not video_file or video_file.filename == '':
                return {"success": False, "message": "未提供有效的视频文件"}
            
            if not text:
                return {"success": False, "message": "未提供水印文本"}
            
            # 保存上传的视频
            filename = str(uuid.uuid4()) + os.path.splitext(video_file.filename)[1]
            upload_folder = os.path.join(VIDEO_DIR, "watermark")
            os.makedirs(upload_folder, exist_ok=True)
            
            input_path = os.path.join(upload_folder, "input_" + filename)
            output_path = os.path.join(upload_folder, "output_" + filename)
            
            video_file.save(input_path)
            
            # 添加水印
            result = self.generator.add_floating_text_watermark(
                video_path=input_path,
                output_path=output_path,
                text=text,
                font_size=font_size,
                font_color=font_color,
                opacity=opacity,
                movement_type=movement_type,
                speed=speed
            )
            
            # 如果处理成功，存储文件信息到数据库
            if result["success"]:
                # 创建视频记录
                meta_data = {
                    "watermark_text": text,
                    "font_size": font_size,
                    "font_color": font_color,
                    "opacity": opacity,
                    "movement_type": movement_type,
                    "speed": speed,
                    "original_filename": video_file.filename
                }
                
                file_record = self.dao_factory.get_uploaded_file_dao().create(
                    file_path=output_path,
                    filename=os.path.basename(output_path),
                    file_type="video",
                    meta_data=meta_data,
                    to_dict=True
                )
                
                result["file_id"] = file_record["id"]
            
            # 处理完成后可以删除输入文件
            if os.path.exists(input_path) and result["success"]:
                try:
                    os.remove(input_path)
                except:
                    pass
                
            return result
            
        except Exception as e:
            log_error(f"添加水印处理出错: {e}")
            return {"success": False, "message": f"处理出错: {str(e)}"}
    
    def add_multiple_watermarks_to_uploaded_video(
        self,
        video_file,
        texts: List[str],
        font_sizes: Optional[List[int]] = None,
        font_colors: Optional[List[str]] = None,
        opacities: Optional[List[float]] = None,
        movement_types: Optional[List[str]] = None,
        speeds: Optional[List[float]] = None
    ) -> Dict[str, Any]:
        """
        为上传的视频添加多个浮动透明水印
        
        Args:
            video_file: 上传的视频文件对象
            texts: 水印文本列表
            font_sizes: 字体大小列表
            font_colors: 字体颜色列表
            opacities: 不透明度列表
            movement_types: 移动类型列表
            speeds: 移动速度列表
        
        Returns:
            处理结果
        """
        try:
            # 检查输入
            if not video_file or video_file.filename == '':
                return {"success": False, "message": "未提供有效的视频文件"}
            
            if not texts or not isinstance(texts, list) or len(texts) == 0:
                return {"success": False, "message": "未提供有效的水印文本列表"}
            
            # 保存上传的视频
            filename = str(uuid.uuid4()) + os.path.splitext(video_file.filename)[1]
            upload_folder = os.path.join(VIDEO_DIR, "watermark")
            os.makedirs(upload_folder, exist_ok=True)
            
            input_path = os.path.join(upload_folder, "input_" + filename)
            output_path = os.path.join(upload_folder, "output_" + filename)
            
            video_file.save(input_path)
            
            # 添加多个水印
            result = self.generator.add_multiple_watermarks(
                video_path=input_path,
                output_path=output_path,
                texts=texts,
                font_sizes=font_sizes,
                font_colors=font_colors,
                opacities=opacities,
                movement_types=movement_types,
                speeds=speeds
            )
            
            # 如果处理成功，存储文件信息到数据库
            if result["success"]:
                # 创建视频记录
                meta_data = {
                    "watermark_texts": texts,
                    "font_sizes": font_sizes,
                    "font_colors": font_colors,
                    "opacities": opacities,
                    "movement_types": movement_types,
                    "speeds": speeds,
                    "original_filename": video_file.filename
                }
                
                file_record = self.dao_factory.get_uploaded_file_dao().create(
                    file_path=output_path,
                    filename=os.path.basename(output_path),
                    file_type="video",
                    meta_data=meta_data,
                    to_dict=True
                )
                
                result["file_id"] = file_record["id"]
            
            # 处理完成后可以删除输入文件
            if os.path.exists(input_path) and result["success"]:
                try:
                    os.remove(input_path)
                except:
                    pass
                
            return result
            
        except Exception as e:
            log_error(f"添加多个水印处理出错: {e}")
            return {"success": False, "message": f"处理出错: {str(e)}"}
    
    def add_watermark_to_video_url(
        self,
        video_url: str,
        text: str,
        font_size: int = 36,
        font_color: str = "white",
        opacity: float = 0.3,
        movement_type: str = "random",
        speed: float = 1.0
    ) -> Dict[str, Any]:
        """
        为指定URL的视频添加浮动透明水印
        
        Args:
            video_url: 视频URL
            text: 水印文本
            font_size: 字体大小
            font_color: 字体颜色
            opacity: 不透明度
            movement_type: 移动类型
            speed: 移动速度
        
        Returns:
            处理结果
        """
        try:
            # 检查输入
            if not video_url:
                return {"success": False, "message": "未提供视频URL"}
            
            if not text:
                return {"success": False, "message": "未提供水印文本"}
            
            # 准备文件路径
            upload_folder = os.path.join(VIDEO_DIR, "watermark")
            os.makedirs(upload_folder, exist_ok=True)
            
            filename = str(uuid.uuid4()) + ".mp4"
            input_path = os.path.join(upload_folder, "input_" + filename)
            output_path = os.path.join(upload_folder, "output_" + filename)
            
            # 下载视频文件
            try:
                log_info(f"开始从URL下载视频: {video_url}")
                response = requests.get(video_url, stream=True, timeout=30)
                response.raise_for_status()
                
                with open(input_path, 'wb') as f:
                    for chunk in response.iter_content(chunk_size=8192):
                        f.write(chunk)
                        
                log_info(f"视频下载成功: {input_path}")
            except Exception as e:
                log_error(f"下载视频失败: {e}")
                return {"success": False, "message": f"下载视频失败: {str(e)}"}
            
            # 添加水印
            result = self.generator.add_floating_text_watermark(
                video_path=input_path,
                output_path=output_path,
                text=text,
                font_size=font_size,
                font_color=font_color,
                opacity=opacity,
                movement_type=movement_type,
                speed=speed
            )
            
            # 如果处理成功，存储文件信息到数据库
            if result["success"]:
                # 创建视频记录
                meta_data = {
                    "watermark_text": text,
                    "font_size": font_size,
                    "font_color": font_color,
                    "opacity": opacity,
                    "movement_type": movement_type,
                    "speed": speed,
                    "original_url": video_url
                }
                
                file_record = self.dao_factory.get_uploaded_file_dao().create(
                    file_path=output_path,
                    filename=os.path.basename(output_path),
                    file_type="video",
                    meta_data=meta_data,
                    to_dict=True
                )
                
                result["file_id"] = file_record["id"]
            
            # 处理完成后可以删除输入文件
            if os.path.exists(input_path) and result["success"]:
                try:
                    os.remove(input_path)
                except:
                    pass
                
            return result
            
        except Exception as e:
            log_error(f"URL视频添加水印处理出错: {e}")
            return {"success": False, "message": f"处理出错: {str(e)}"}
        
    def add_floating_image_watermark(
        self,
        video_folder: str,
        image_file,
        opacity: float = 1,
        movement_type: str = "random",
        scale: float = 1.0,
        speed: float = 1.0
    ) -> Dict[str, Any]:
        """
        为文件夹中所有MP4视频添加浮动图片水印

        Args:
            video_folder: 输入视频文件夹路径
            image_file: 水印图片文件对象
            opacity: 不透明度 (0.0-1.0)
            movement_type: 移动类型 ("random", "diagonal", "bounce", "circular")
            scale: 图片缩放比例
            speed: 水印移动速度

        Returns:
            处理结果字典
        """
        log_info(f"处理浮动图片水印请求: video_folder={video_folder}")

        try:
            results = {
                "processed_videos": [],
                "failed_videos": []
            }
            
            # 确保文件夹存在
            if not os.path.exists(video_folder) or not os.path.isdir(video_folder):
                raise ValueError(f"无效的视频文件夹: {video_folder}")
            
            # 获取文件夹中所有的MP4文件
            mp4_files = [f for f in os.listdir(video_folder) if f.lower().endswith('.mp4')]
            
            if not mp4_files:
                raise ValueError(f"文件夹中未找到MP4视频文件: {video_folder}")
            
            # 使用TempFile处理水印图片
            output_folder = os.path.join(VIDEO_DIR, "watermark")
            os.makedirs(output_folder, exist_ok=True)
            
            # 创建临时文件
            # Create a temporary image file using FileManager
            file_manager = FileManager()
            temp_image_path = file_manager.create_temp_file(category="watermark").path
            
            try:
                # Save image file to temporary path
                image_file.save(temp_image_path)
                
                # Process each MP4 file
                for mp4_file in mp4_files:
                    video_path = os.path.join(video_folder, mp4_file)
                    output_path = os.path.join(output_folder, f"output_{uuid.uuid4()}.mp4")
                    
                    try:
                        # Add watermark
                        result = self.generator.add_floating_image_watermark(
                            video_path=video_path,
                            output_path=output_path,
                            image_path=temp_image_path,
                            opacity=opacity,
                            movement_type=movement_type,
                            scale=scale,
                            speed=speed
                        )
                        
                        result["original"] = mp4_file
                        if result["success"]:
                            results["processed_videos"].append(result)
                        else:
                            result["error"] = result["message"]
                            results["failed_videos"].append(result)
                            
                    except Exception as e:
                        log_error(f"处理视频 {mp4_file} 时出错: {str(e)}")
                        results["failed_videos"].append({
                            "original": mp4_file,
                            "error": str(e)
                        })
            finally:
                # Clean up the temporary image file
                file_manager.cleanup_category("watermark")
            
            return results
        except Exception as e:
            raise Exception(f"添加浮动图片水印时出错: {str(e)}") from e